package com.oocl.products.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.products.pojo.Product;
import com.oocl.products.pojo.Store;
import com.oocl.products.service.ProductService;
import com.oocl.products.service.StoreService;
import com.oocl.products.service.factory.ProductServiceFactory;
import com.oocl.products.service.factory.StoreServiceFactory;
import com.oocl.products.util.StringUtil;


public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private ProductService productService;
	private StoreService storeService;
	
	public ProductServlet() {
		productService = ProductServiceFactory.getInstance();
		storeService = StoreServiceFactory.getInstance();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Store> stores = storeService.queryAllStore();
		request.setAttribute("stores", stores);
		request.getRequestDispatcher("product.jsp").forward(request, response);;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String priceStr = request.getParameter("price");
		String totalStr = request.getParameter("total");
		String pdStr = request.getParameter("pd");
		String sidStr = request.getParameter("store");
		Double price = null;
		Integer total = null;
		Date pd = null;
		Integer sid = null;
		try {
			price = Double.parseDouble(priceStr);
			total = Integer.parseInt(totalStr);
			pd = StringUtil.getFormatDate(pdStr);
			sid = Integer.parseInt(sidStr);
		} catch (Exception e) {
			//Exception
			request.setAttribute("error", "parameter format error");
			request.getRequestDispatcher("../error.jsp").forward(request, response);
		}
		
		Product product = new Product(StringUtil.createRandomStr(), name, price, total, pd, sid);
		//Add
		if(productService.addProduct(product)){
			response.sendRedirect("list?sid="+sid);
		}else{
			request.setAttribute("error", "add product error");
			request.getRequestDispatcher("../error.jsp").forward(request, response);
		}
	}

}
